import React, { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { UploadOutlined } from '@ant-design/icons';
import { Button, Card, Cascader, Checkbox, Form, Input, InputNumber, PageHeader, Space, Steps, Tabs, Upload } from 'antd'
import { getCategories } from "../../api/categories.js"
import { getCategoriesParam } from "../../api/params.js";
import { getGoodsById, addGoods, editGoods } from "../../api/goods.js";
import PageBreadcrumb from '../../components/PageBreadcrumb'
import Message from '../../components/Message'
import { getItem } from '../../utils/storage'
import WangEditor from './WangEditor'

const { Step } = Steps;
const { TabPane } = Tabs;

const AddOrEditGoods = () => {
  let api = ''
  if (process.env.NODE_ENV === "development") {
    api = process.env.REACT_APP_DEVLOPMENT_API_URL
  } else {
    api = process.env.REACT_APP_PRODUCTION_API_URL
  }
  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };
  const user = getItem('user')
  const headersObj = {
    //图片上传组件的headers请求头
    Authorization: user.token,
  };
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { id } = useParams()

  const [loading, setLoading] = useState(false)
  const [activeKey, setActiveKey] = useState("0")
  const [current, setCurrent] = useState(0)
  const [cateList, setCateList] = useState([])
  const [cateId, setCateId] = useState(null); // 当前选中的商品分类ID
  const [manyData, setManyData] = useState([]); //商品参数
  const [onlyData, setOnlyData] = useState([]); //商品属性
  const uploadURL = api + "/upload"; //上传图片的URL地址
  const [fileList, setFileList] = useState([]) //上传图片列表
  const [content, setContent] = useState([]) //富文本内容

  useEffect(() => {
    getCateList()
    if (id) {
      loadDataInfo()
    }
  }, [])

  useEffect(() => {
    if (current === 1) {
      //获取商品参数
      getParamsData("many");
    } else if (current === 2) {
      //获取商品属性
      getParamsData("only");
    }
  }, [current, activeKey])


  // 编辑页面时请求数据
  const loadDataInfo = async () => {
    const data = await getGoodsById(id);

    data.goods_cat = data.goods_cat.split(",").map(Number);
    form.setFieldsValue(data)

    let many = []
    let only = []
    data.attrs.forEach((item) => {
      if (item.attr_write === "list") {
        many.push(item)
      } else {
        only.push(item)
      }
    });
    many.forEach((item) => {
      item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
    });
    setCateId(data.goods_cat[2])
    setManyData(many)
    setOnlyData(only)
    setContent(data.goods_introduce)
    // 商品图片
    if (data.pics.length > 0) {
      const file = data.pics.map((item, index) => {
        return {
          uid: item.pics_id + index,
          name: item.pics_id,
          status: 'done',
          url: item.pics_big_url,
          thumbUrl: item.pics_big
        };
      });
      setFileList(file)
    }

  };

  // 获取商品分类
  const getCateList = async () => {
    const data = await getCategories();
    setCateList(data)
  };

  // 选择商品分类
  const cateChange = (value) => {
    setCateId(value.length == 3 ? value[2] : null)
  };

  // tab 被选中时触发
  const tabClicked = () => {
    if (!cateId) {
      Message('error', '请先选择商品分类！')
      setActiveKey('0')
      setCurrent(0)
      return
    }
  };

  // 获取参数列表数据
  const getParamsData = async (type) => {
    if (cateId && type) {
      // 根据所选分类ID和当前所处的面板获取对应的参数
      const data = await getCategoriesParam(cateId, type);

      if (type === "many") {
        data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
        setManyData(data)
      } else {
        setOnlyData(data)
      }
    }
  };

  // 返回商品列表
  const goBack = () => {
    navigate("/goods");
  };

  // 切换步骤
  const onChangeStep = (current) => {
    setActiveKey(current + "")
    setCurrent(current)
    tabClicked()
  }

  // 切换步骤
  const onChangeTab = (current) => {
    setActiveKey(current)
    setCurrent(current - 0)
    tabClicked()
  }

  // 图片上传成功时的钩子
  const handleSuccess = (info) => {
    setFileList(info.fileList)
  };

  const changeContent = (content) => {
    setContent(content)
  }

  // 点击完成
  const onFinish = async (values) => {
    setLoading(true)
    let data = { ...values }
    let attrs = []
    // 处理动态参数
    manyData.forEach(item => {
      const newInfo = {
        attr_id: item.attr_id,
        attr_value: item.attr_vals.join(" "),
      };
      attrs.push(newInfo)
    })
    // 处理静态属性
    onlyData.forEach(item => {
      const newInfo = {
        attr_id: item.attr_id,
        attr_value: item.attr_vals,
      };
      attrs.push(newInfo);
    })
    data.attrs = attrs
    data.goods_cat = data.goods_cat.join(",")
    let pics = []
    if (fileList.length > 0) {
      fileList.forEach(item => {
        const picInfo = {
          pic: item.response.data.tmp_path,
        };
        pics.push(picInfo)
      })
    }
    data.pics = pics
    data.goods_introduce = content

    if (id) {
      // 编辑商品
      await editGoods(id, data).finally(() => {
        setLoading(false)
      });
      Message("success", "编辑成功")
    } else {
      // 添加商品
      await addGoods(data).finally(() => {
        setLoading(false)
      });
      Message("success", "添加成功")
    }
    goBack()
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const hideDropdown = (value) => {
    console.log(value)
  }

  return (
    <>
      <PageBreadcrumb>
        <span>商品管理</span>
        <span>{id ? "编辑商品" : "添加商品"}</span>
      </PageBreadcrumb>

      <Card>
        <PageHeader
          title={id ? "编辑商品" : "添加商品"}
          onBack={goBack}
        />
        <Steps size="small" current={current} onChange={onChangeStep}>
          <Step title="基本信息" />
          <Step title="商品参数" />
          <Step title="商品属性" />
          <Step title="商品图片" />
          <Step title="商品内容" />
          <Step title="完成" />
        </Steps>

        <Form
          form={form}
          layout="vertical"
          autoComplete="off"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Tabs activeKey={activeKey} tabPosition="left" onChange={onChangeTab}>
            <TabPane key="0" tab="基本信息">
              <Form.Item
                label="商品名称"
                name="goods_name"
                rules={[{ required: true, message: '请输入商品名称' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="商品价格"
                name="goods_price"
                rules={[{ required: true, message: '请输入商品价格' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
                label="商品重量"
                name="goods_weight"
                rules={[{ required: true, message: '请输入商品重量' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
                label="商品数量"
                name="goods_number"
                rules={[{ required: true, message: '请输入商品数量' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
                label="商品分类"
                name="goods_cat"
                rules={[{ required: true, message: '请输入商品分类' }]}
              >
                <Cascader
                  fieldNames={{
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children',
                  }}
                  options={cateList}
                  onChange={cateChange}
                  expandTrigger="hover"
                  allowClear={true}
                  onDropdownVisibleChange={hideDropdown}
                />
              </Form.Item>
            </TabPane>

            <TabPane key="1" tab="商品参数">
              {
                manyData.map((item) =>
                  <Form.Item key={item.attr_id} label={item.attr_name}>
                    <Checkbox.Group value={item.attr_vals}>
                      {
                        item.attr_vals.map((item2) =>
                          <Checkbox key={item2} value={item2} disabled={true}>{item2}</Checkbox>
                        )
                      }
                    </Checkbox.Group>
                  </Form.Item>
                )
              }
            </TabPane>

            <TabPane key="2" tab="商品属性">
              {
                onlyData.map((item) =>
                  <Form.Item key={item.attr_id} label={item.attr_name}>
                    <Input defaultValue={item.attr_vals} disabled={true} />
                  </Form.Item>
                )
              }
            </TabPane>

            <TabPane key="3" tab="商品图片">
              <Upload
                action={uploadURL}
                headers={headersObj}
                fileList={fileList}
                listType="picture"
                onChange={handleSuccess}
              >
                <Button icon={<UploadOutlined />}>点击上传</Button>
                <p>
                  图片格式为 image/png, image/jpeg, image/jpg,
                </p>
              </Upload>
            </TabPane>

            <TabPane key="4" tab="商品内容">
              <WangEditor changeContent={changeContent} content={content} id={id} />
            </TabPane>
          </Tabs>
          {
            current === 4 ?
              <Form.Item {...tailLayout}>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    style={{ 'marginTop': '20px' }}
                    loading={loading}
                  >添加</Button>
                </Space>
              </Form.Item>
              : null
          }
        </Form>
      </Card>
    </>
  )
}

export default AddOrEditGoods